package com.tianji.learning.service.impl;

import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.leanring.LearningLessonDTO;
import com.tianji.api.dto.leanring.LearningRecordDTO;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.LearningRecordFormDTO;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.domain.po.LearningRecord;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.enums.SectionType;
import com.tianji.learning.mapper.LearningRecordMapper;
import com.tianji.learning.service.ILearningLessonService;
import com.tianji.learning.service.ILearningRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.learning.task.LearningRecordDelayTaskHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 学习记录表 服务实现类
 * </p>
 *
 * @author yp
 * @since 2024-07-20
 */
@Service
@RequiredArgsConstructor
public class LearningRecordServiceImpl extends ServiceImpl<LearningRecordMapper, LearningRecord> implements ILearningRecordService {

    private final ILearningLessonService lessonService;
    private final CourseClient courseClient;
    private final LearningRecordDelayTaskHandler taskHandler;

    /**
     * 根据课程id查询学习记录
     *
     * @param courseId
     * @return
     */
    @Override
    public LearningLessonDTO queryByCourseId(Long courseId) {
        //1.根据courserId和userId查询出课表
        Long userId = UserContext.getUser();
        LearningLesson lesson = lessonService.lambdaQuery()
                .eq(LearningLesson::getCourseId, courseId)
                .eq(LearningLesson::getUserId, userId)
                .one();
        if (lesson == null) {
            return null;
        }
        //2.根据课表id查询出学习记录列表
        Long LessonId = lesson.getId();
        List<LearningRecord> list = lambdaQuery()
                .eq(LearningRecord::getLessonId, LessonId)
                .list();
        List<LearningRecordDTO> records = BeanUtils.copyList(list, LearningRecordDTO.class);
        //3.封装LearningLessonDTO
        LearningLessonDTO dto = new LearningLessonDTO();
        dto.setId(LessonId);
        dto.setLatestSectionId(lesson.getLatestSectionId());
        dto.setRecords(records);

        return dto;
    }

    /**
     * 提交学习记录
     *
     * @param dto
     */
    @Override
    @Transactional
    public void addLearningRecord(LearningRecordFormDTO dto) {
        //1.获得用户id
        Long userId = UserContext.getUser();
        //2.处理学习记录
        //2.1 判断提交的类型
        //判断是否学完小节finished
        boolean finished = false;
        if (dto.getSectionType() == SectionType.EXAM) {
            //2.2处理考试
            finished = handleExam(userId, dto);
        } else {
            //2.3处理视频
            finished = handleVedio(userId, dto);

        }
        //如果没有小节学完
        if (!finished) {
            return;
        }
        //3.处理课表
        handleLesson(dto);

    }

    /**
     * 处理课表
     *
     * @param dto
     */
    private void handleLesson(LearningRecordFormDTO dto) {
        //1.根据课表id查询课表
        LearningLesson old = lessonService.getById(dto.getLessonId());
        if (old == null) {
            throw new DbException("课表数据不存在");
        }
        //2.判断是否全部学完(查询当前的课程的小节总数，就已经学习的小-小节数 >= 当前课程的小节数)
        //有小节学完才有必要去判断是否全部学完
        boolean allLeaned = false;
        //  if(finished){
        CourseFullInfoDTO course = courseClient.getCourseInfoById(old.getCourseId(), false, false);
        if (course != null) {
            Integer sectionNum = course.getSectionNum();
            allLeaned = old.getLearnedSections() + 1 >= sectionNum;
//            }
        }
        //3。更新课表()
        boolean success = lessonService.lambdaUpdate()
                .set(LearningLesson::getLatestSectionId, dto.getSectionId())
                .set(LearningLesson::getLatestLearnTime, LocalDateTime.now())
                .set(LearningLesson::getLearnedSections, old.getLearnedSections() + 1)
                .set(allLeaned, LearningLesson::getStatus, LessonStatus.FINISHED)
                .set(old.getStatus() == LessonStatus.NOT_BEGIN, LearningLesson::getStatus, LessonStatus.LEARNING)//如果这门课第一次学习
                .eq(LearningLesson::getId, old.getId())
                .update();
        if (!success) {
            throw new DbException("课表更新失败");
        }
    }

    /**
     * 处理视频
     *
     * @param userId
     * @param dto
     * @return
     */
    private boolean handleVedio(Long userId, LearningRecordFormDTO dto) {
        //1.根据课表id和小节id查询学习记录
//        LearningRecord old = lambdaQuery()
//                .eq(LearningRecord::getLessonId, dto.getLessonId())
//                .eq(LearningRecord::getSectionId, dto.getSectionId())
//                .one();
        LearningRecord old = queryLearningRecord(dto);
        //2.不存在。新增学习记录
        if (old == null) {
            //1.创建Record对象
            LearningRecord learningRecord = BeanUtils.copyBean(dto, LearningRecord.class);
            //2.设置属性(用户id，是否完成，完成的时间)
            learningRecord.setUserId(userId);
            boolean success = save(learningRecord);
            if (!success) {
                throw new DbException("保存学习视频记录失败");
            }
            return false;
        }
        //3.判断是否为第一次学完
        boolean finished = !old.getFinished() && dto.getMoment() * 2 > dto.getDuration();
        //4.更新学习记录
        if (!finished) {
            //不是第一次学完，缓存到redis里面。提交延迟任务
            LearningRecord record = new LearningRecord();
            record.setLessonId(dto.getLessonId());
            record.setSectionId(dto.getSectionId());
            record.setMoment(dto.getMoment());
            record.setId(old.getId());
            record.setFinished(old.getFinished());
            taskHandler.addLearningRecordTask(record);
            return false;
        }
        boolean success = lambdaUpdate()
                .set(LearningRecord::getMoment, dto.getMoment())
                .set(LearningRecord::getFinished, true)
                .set(LearningRecord::getFinishTime, dto.getCommitTime())
                .eq(LearningRecord::getId, old.getId())
                .update();
        if (!success) {
            throw new DbException("更新学习进度视频失败");
        }
        //清理redis数据
        taskHandler.cleanRecordCache(dto.getLessonId(), dto.getSectionId());
        return true;
    }

    /**
     * 查询当前课程小结的学习记录
     *
     * @param dto
     * @return
     */
    private LearningRecord queryLearningRecord(LearningRecordFormDTO dto) {
        // 1.先从Redis里面查询
        LearningRecord learningRecord = taskHandler.readRecordCache(dto.getLessonId(), dto.getSectionId());

        // 2.没有再从mysql查询
        if (learningRecord == null) {
            //1.根据课表id和小节id查询学习记录
            learningRecord = lambdaQuery()
                    .eq(LearningRecord::getLessonId, dto.getLessonId())
                    .eq(LearningRecord::getSectionId, dto.getSectionId())
                    .one();
            if (learningRecord != null) {
                //存在redis里面
                taskHandler.writeRecordCache(learningRecord);
            }
        }
        return learningRecord;
    }

    /**
     * 处理考试
     *
     * @param userId
     * @param dto
     * @return
     */
    private boolean handleExam(Long userId, LearningRecordFormDTO dto) {
        //1.创建Record对象
        LearningRecord learningRecord = BeanUtils.copyBean(dto, LearningRecord.class);
        //2.设置属性(用户id，是否完成，完成的时间)
        learningRecord.setUserId(userId);
        learningRecord.setFinished(true);
        learningRecord.setFinishTime(dto.getCommitTime());
        //3.保存
        boolean success = save(learningRecord);
        if (!success) {
            throw new DbException("保存考试记录失败");
        }
        return true;
    }

}
